package org.example.MVC2;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class FilesController {
    @RequestMapping("/filesPage")
    public String filesPage(){
        return "files";
    }

    //文件上传
    @RequestMapping("/fileUpload")
    public String fileUpload(MultipartFile filename) throws IOException {
        System.out.println("filename="+filename.getOriginalFilename());    //文件名
        if(!filename.isEmpty()){      //判断是否为空
            //保存上传的文件，filepath为保存目标目录
            filename.transferTo(new File("filepath"));       //transferTo()方法用于将接收文件传输到指定目标路径
            return "success";
        }
        return "files";
    }

    //文件下载
    @RequestMapping("/download")
    public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename) throws IOException {
        //指定要下载的文件所在路径
        String path = request.getServletContext().getRealPath("/filepath/abc");
        //创建该文件对象
        File file = new File(path+File.separator+filename);
        //设置消息头
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以下载的方式打开文件
        headers.setContentDispositionFormData("attachment",filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //使用String MVC框架的ResponseEntity对象封装返回下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }
}
